package com.atguigu.day10;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class Flink02_TableToDs {

    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //1.1 创建表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 2.创建流
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = socketTextStream.map(line -> {
            String[] fields = line.split(",");
            return new WaterSensor(fields[0],
                    Long.parseLong(fields[1]),
                    Integer.parseInt(fields[2]));
        });

        //TODO 3.将流转换为动态表
        Table sensorTable = tableEnv.fromDataStream(waterSensorDS);

        //TODO 4.使用TableAPI 简单查询
        Table resultTable = sensorTable
                .where($("id").isEqual("1001"))
//                .groupBy($("id"))
//                .aggregate($("vc").sum().as("vc"))
                .select($("id"), $("vc"));

        //TODO 5.将动态表转换为流进行打印
        tableEnv.toDataStream(resultTable).print("toDataStream>>>>>>");
        tableEnv.toAppendStream(resultTable, Row.class).print("toAppendStream>>>>>>");
        tableEnv.toChangelogStream(resultTable).print("toChangelogStream>>>>");
        tableEnv.toRetractStream(resultTable, Row.class).print("toRetractStream>>>>");

        //TODO 6.启动任务
        env.execute();

    }

}
